import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {withRouter} from 'react-router';
import {renderRoutes} from 'react-router-config';

import {Common} from './components';
import {LineLoading} from '../../components';

import utils from '../../utils';
import {getUserInfo} from './redux';

import '../../assets/css/main.css';
import '../../assets/theme/theme.less';

class App extends Component {

    constructor(props) {
        super(props);

        this.state = {
            pathname: this.props.location.pathname || '/'
        };

        if (!this.bounded) {
            this.props.history.listen((location, action) => {
                this.handleRouterChange(location);
            });

            this.bounded = true;
        }
    }

    static contextTypes = {
        router: PropTypes.any
    };

    handleRouterChange = location => {
        this.setState({pathname: location.pathname});
    };

    componentDidMount() {
        if (!this.props.loadover) {
            this.props.getUserInfo();
        }
    }

    render() {
        const pathname = this.state.pathname;
        const {userInfo, loading, route, loadover} = this.props;

        return (
            <div>
                <Common pathname={pathname} userInfo={userInfo}>
                    {renderRoutes(route.routes)}
                </Common>
            </div>
        );
    }
}

function mapStateToProps(state) {
    const {lineloading, data, loadover} = state.app;

    return {
        loading: lineloading,
        userInfo: data,
        loadover
    };
}

function mapDispatchToProps(dispatch) {
    return {
        getUserInfo() {
            return dispatch(getUserInfo());
        }
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(withRouter(App));
